import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:management/const/consts.dart';
import 'package:management/const/flags.dart';
import 'package:management/const/init.dart';
import 'package:management/const/theme.dart';
import 'package:management/data/network/api/api.dart';
import 'package:management/element/loading.dart';
import 'package:management/element/toast.dart';
import 'package:management/main.dart';

import 'state.dart';

class ProfileScreenLogic extends GetxController {
  final ProfileScreenState state = ProfileScreenState();

  @override
  void onInit() {
    super.onInit();
    _initData();
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  void click(int index) {
    switch (index) {
      case 0:
        Get.toNamed(RouteConfig.workSpaceScreen);
      case 1:
        Get.toNamed(RouteConfig.editProfileScreen);
      case 2:
        Get.toNamed(RouteConfig.notificationScreen);
      case 3:
        Get.toNamed(RouteConfig.securityScreen);
      case 6:
        Get.bottomSheet(
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 24),
            child: Wrap(children: [
              SizedBox(
                height: 330,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Text(MyText.logout.tr,
                        style: Theme.of(Get.context!)
                            .textTheme
                            .titleLarge
                            ?.copyWith(color: MyColor.error)),
                    Divider(
                      thickness: 1,
                      color: MyColor.grayScale[200],
                    ),
                    Text(
                      MyText.logoutSure.tr,
                      style: Theme.of(Get.context!).textTheme.titleMedium,
                    ),
                    SizedBox(
                        width: double.infinity,
                        height: 55,
                        child: ElevatedButton(
                            style: Theme.of(Get.context!)
                                .elevatedButtonTheme
                                .style
                                ?.copyWith(
                                  elevation: MaterialStateProperty.all(0),
                                ),
                            onPressed: () => _logOutYes(),
                            child: Text(MyText.logoutYes.tr))),
                    SizedBox(
                      width: double.infinity,
                      height: 55,
                      child: ElevatedButton(
                          style: Theme.of(Get.context!)
                              .elevatedButtonTheme
                              .style
                              ?.copyWith(
                                  elevation: MaterialStateProperty.all(0),
                                  backgroundColor: Get.isDarkMode
                                      ? MaterialStateProperty.all(MyColor.dark3)
                                      : MaterialStateProperty.all(
                                          MyColor.primary[200])),
                          onPressed: () => _logOutCancel(),
                          child: Text(MyText.cancel.tr)),
                    ),
                  ],
                ),
              ),
            ]),
          ),
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(40), topRight: Radius.circular(40)),
          ),
          backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor,
        );
    }
  }

  void changeTheme(bool state) {
    Get.changeTheme(state ? AppTheme.darkTheme : AppTheme.lightTheme);
  }

  void _logOutYes() {
    String? isRemember = GlobalInit.getSpData(SPFlag.password);
    // GlobalInit.removeLoginStatus();
    Get.offAllNamed(RouteConfig.welcomeScreen);
  }

  void _logOutCancel() {
    Get.back();
  }

  void _getUserDate() {
    // TODO: 实现本地缓存
    MyHttpClient.getUserData().then((value) {
      if (value.code == 200) {
        state.name.value = value.data!.nickName!;
        state.headImage.value = value.data!.avatar!;
      } else {
        String? name = GlobalInit.getSp().getString(SPFlag.nickName);
        state.name.value = name ?? MyText.defaultName.tr;
        Utils.toastError(MyText.getUserDataFailure.tr);
      }
    });
  }

  void _initData() {
    _getUserDate();
  }

  void refreshProfileScreen() {
    _initData();
  }

  void changeAvatar() {
    Get.bottomSheet(
        Wrap(
          children: <Widget>[
            Container(
              padding: const EdgeInsets.symmetric(vertical: 2),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => _getLostData(0),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.picFromCamera.tr,
                      style: Theme.of(Get.context!).textTheme.bodyLarge,
                    ),
                  ],
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(vertical: 2),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => _getLostData(1),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.picFromAlbum.tr,
                      style: Theme.of(Get.context!).textTheme.bodyLarge,
                    ),
                  ],
                ),
              ),
            ),
            Container(
              padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 5),
              width: double.infinity,
              height: 60,
              child: TextButton(
                onPressed: () => Get.back(),
                style: Theme.of(Get.context!).textButtonTheme.style,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      MyText.cancel.tr,
                      style: Theme.of(Get.context!)
                          .textTheme
                          .bodyLarge
                          ?.copyWith(color: MyColor.error),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
        isDismissible: false,
        backgroundColor: Theme.of(Get.context!).scaffoldBackgroundColor);
  }

  Future<void> _getLostData(int type) async {
    final XFile? file = await ImagePicker().pickImage(
        source: type == 0 ? ImageSource.camera : ImageSource.gallery,
        maxWidth: 120);
    if (file == null) {
      return;
    }
    LoadingElement.loadingDialog(true);
    MyHttpClient.uploadFile(file.path, file.name).then((value) {
      if (value.code == 200) {
        MyHttpClient.updateUserData({'avatar': value.data?.url}).then((value) {
          if (value.code == 200) {
            Get.back();
            Get.back();
            _initData();
          }
        }).onError((error, stackTrace) {
          Utils.toastError(error);
          Get.back();
        });
      } else {
        Utils.toastError(value.msg);
        Get.back();
      }
    }).onError((error, stackTrace) {
      Utils.toastError(error);
      Get.back();
    });
  }

  void _handleLostFiles(List<XFile> files) {}
}
